﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;

namespace OrganizedIN.UI
{
    public partial class PhotoUploader : System.Web.UI.Page
    {
        OIDataContext dc = new OIDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            lblStatus.Text = "";
            if (Session["UserID"] != null)
            {
                if (!IsPostBack)
                {
                    var photo = (from d in dc.UserInformations
                                 where d.username == Session["UserID"].ToString()
                                 select d.ProfilePicture).SingleOrDefault();
                    if (photo != null && photo != "")
                    {
                        userImage.ImageUrl = photo;
                    }
                    else
                    {
                        userImage.ImageUrl = "~/images/user-icon.jpg";
                    }
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string strFilename = string.Empty, strExt = string.Empty;
            string strUploadPath = "";
            string RelativePath = "";
            strFilename = txtFileUpload.FileName.ToString();
            //char[] unallowed = new char[] { '<', '>', ':', '"', '/', '\\', '|', '?', '*' };
            if (txtFileUpload.HasFile)
            {
                strExt = System.IO.Path.GetExtension(strFilename).ToLower();
                if (strExt == ".bmp" || strExt == ".jpg" || strExt == ".png" || strExt == ".jpeg" || strExt == ".gif")
                {
                    string uname = Session["UserID"].ToString();
                    //foreach (char c in unallowed)
                    //{
                    //    uname.Replace(c, '_');
                    //}
                    //if (!Directory.Exists(Server.MapPath("~/ProfilePhotos/" + uname)))
                    //{
                    //    Directory.CreateDirectory(Server.MapPath("~/ProfilePhotos/" + uname));
                    //}
                    //strUploadPath = Server.MapPath("~/ProfilePhotos/" + uname);
                    strUploadPath = Server.MapPath("~/ProfilePhotos/");
                    RelativePath = "~/ProfilePhotos/";
                    strFilename = Path.GetFileNameWithoutExtension(strFilename);
                    strFilename += (new Random(4000)).Next().ToString();
                    strFilename += strExt;
                    strUploadPath += strFilename;
                    RelativePath += strFilename;
                    txtFileUpload.PostedFile.SaveAs(strUploadPath);
                    var data = (from d in dc.UserInformations
                                where d.username == Session["UserID"].ToString()
                                select d).SingleOrDefault();
                    data.ProfilePicture = RelativePath;
                    dc.SubmitChanges();
                    ResizeImage(strUploadPath, strUploadPath, 100, 120, true);
                    userImage.ImageUrl = RelativePath;
                    lblStatus.ForeColor = Color.Green;
                    lblStatus.Text = "Your Profile Picture Has Been Changed Successfully !";
                }
                else
                {
                    lblStatus.ForeColor = Color.Red;
                    lblStatus.Text = "Only upload bmp,jpg,jpeg,png,gif kind of files";
                }
            }
            else
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Please select a file";
            }
        }

        public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            // Save resized picture
            NewImage.Save(NewFile);
        }
    }
}

